var WxParse = require('../wxParse/wxParse.js');

export function getAIResponse(userMessage, imageUrl, page) {
  const conversationId = page.data.conversationId || ''; // 从页面数据中获取会话ID，如果没有则为空
  console.log('conversationId',conversationId)
  const userId = wx.getStorageSync('userInfo').userId; // 假设用户唯一标识存在于用户信息中
  const messageId = page.data.messageId || ''; // 存储消息的 message_id

  const requestData = {
    query: userMessage,
    response_mode: 'streaming',
    conversation_id: conversationId,
    user: userId,
  };

  // 如果有图片 URL，则添加到 files 字段
  if (imageUrl) {
    requestData.files = [{
      type: 'image',
      url: imageUrl,
    }];
  }

  wx.request({
    url: 'https://open.oppomobile.com/agentplatform/app_api/chat', // 替换为实际的接口地址
    method: 'POST',
    header: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer Rfl0IQuZR9vBT75i' // 替换为实际的认证令牌
    },
    data: requestData,
    success: (res) => {
      handleAIResponse(res.data, page);
    },
    fail: (err) => {
      wx.showToast({
        title: '请求失败',
        icon: 'none',
      });
      console.error('Request failed:', err);

      // 更新最后一个消息为失败状态
      const messages = page.data.messages;
      if (messages.length > 0 && messages[messages.length - 1].role === 'ai') {
        messages[messages.length - 1].isLoading = false; // 停止显示加载图标
        messages[messages.length - 1].content = '请求失败，请重试。'; // 显示失败信息
        page.setData({
          messages: messages,
        });
      }
    },
  });
}

function handleAIResponse(data, page) {
  if (!data) return;

  let combinedAnswer = '';
  let imageUrls = [];
  let conversationId = page.data.conversationId;
  let messageId = page.data.messageId || '';

  const lines = data.split('\n');

  lines.forEach((line) => {
    if (line.startsWith('data: ')) {
      line = line.substring(6).trim();
    }
    try {
      if (line === '' || line === 'ping') return;
      const jsonData = JSON.parse(line);
      if (jsonData.event === 'agent_message') {
        const messageContent = jsonData.answer;
        if (messageContent) {
          combinedAnswer += messageContent.replace(/\\n/g, '\n');
        }
        if (jsonData.conversation_id) {
          conversationId = jsonData.conversation_id;
        }
        if (jsonData.message_id) {
          messageId = jsonData.message_id;
        }
      } else if (jsonData.event === 'message_file') {
        if (jsonData.type === 'image' && jsonData.url) {
          imageUrls.push(jsonData.url);
        }
      }
    } catch (e) {
      console.error('Error parsing line:', line, e);
    }
  });
   // 检查并处理 combinedAnswer 中的纯图片路径
  console.log("ai回答：",combinedAnswer)
  const messages = page.data.messages;

  if (messages.length > 0 && messages[messages.length - 1].role === 'ai' && messages[messages.length - 1].isLoading) {
    const loadingMessageIndex = messages.length - 1;
    messages[loadingMessageIndex].isLoading = false;

    // 如果 combinedAnswer 有内容，更新 content 和 displayContent
    if (combinedAnswer.trim()) {
      messages[loadingMessageIndex].content = combinedAnswer.trim();

      // 使用 WxParse 解析 Markdown 内容
      WxParse.wxParse('parsedAnswer', 'md', combinedAnswer.trim(), page, 5);
      const parsedImages = page.data.parsedAnswer.nodes.filter(node => node.tag === 'img').map(node => node.attr.src);
      // 更新消息的 displayContent 为解析后的内容
      messages[loadingMessageIndex].displayContent = page.data.parsedAnswer.nodes;
      console.log("page.data.parsedAnswer",page.data.parsedAnswer)
      page.setData({
        imageUrls: parsedImages, // 保存图片 URL 列表
      });
      console.log('imageUrls',imageUrls)
    }
    // 如果有图片，追加图片到当前消息
    if (imageUrls.length > 0) {
      imageUrls.forEach(url => {
        messages.push({
          role: 'ai',
          content: url,
          isImage: true,
          isLoading: false,
        });
      });
    }
  }
// 标记最新消息
  messages[messages.length - 1].isLatest = true;
  page.setData({
    messages: messages,
    conversationId: conversationId,
    messageId: messageId,
  });

  if (messageId) {
    getAISuggestions(messageId, page);
  }
}
// 获取 AI 建议的函数保持不变
function getAISuggestions(messageId, page) {
  const userId = wx.getStorageSync('userInfo').userId; // 获取用户唯一标识

  wx.request({
    url: `https://open.oppomobile.com/agentplatform/app_api/messages/${messageId}/suggestions`,
    method: 'GET',
    header: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer Rfl0IQuZR9vBT75i`
    },
    data: {
      user: userId,
    },
    success: (res) => {
      if (res.data.result === 'success') { // 使用 'result' 字段判断成功
        const suggestions = res.data.data;
        console.log('AI 提问建议:', suggestions);

        // 获取当前的消息数组
        const messages = page.data.messages || [];

        // 将每个建议添加到消息数组中
        suggestions.forEach(suggestion => {
          messages.push({
            role: 'suggestion',
            content: suggestion,
            isImage: false,
          });
        });

        // 更新页面数据以便在 UI 中显示建议
        page.setData({
          messages: messages,
        });
      } else {
        console.error('获取建议失败:', res.data.msg);
        wx.showToast({
          title: '获取建议失败',
          icon: 'none',
        });
      }
    },
    fail: (err) => {
      console.error('请求失败:', err);
      wx.showToast({
        title: '请求失败',
        icon: 'none',
      });
    }
  });
}

